<?php
namespace app\api\controller;
use app\common\controller\Frontend;
use EasyWeChat\Factory;
use think\Log;
use app\common\model\User;
use think\Request;
use think\Session;
use think\Db;

class Mpwechat extends Frontend {
    protected $mpWecaht;
    protected function _initialize(){
        parent::_initialize();
        $this->mpWecaht = Factory::officialAccount(config('wechat'));
    }

    public function callback(Request $request){
        $redirect = $redirect = $this->mpWecaht->oauth->scopes(['snsapi_userinfo'])->redirect(url('mpwechat/oauth',['skip'=>'register_index'],false,true));
        dump($redirect);
    }
    public function baseoauth(){
        // 获取 OAuth 授权结果用户信息
        $code = input('code','');
        $skip = input('skip','');
        if($code == ''){
            die('授权失败');
        }
        $oauth = $this->mpWecaht->oauth->scopes(['snsapi_base']);
        $user = $oauth->userFromCode($code);
        $openid = $user->getId();
        if($openid){
            if($this->auth->loginOpenid($openid)==false){
                Session::set('lifeOpenid',$openid);
            }
        }
        return  redirect(url(str_replace('_','/',$skip)));
    }
    public function oauth(){
        // 获取 OAuth 授权结果用户信息
        $code = input('code','');
        $skip = input('skip','');
        if($code == ''){
            die('授权失败');
        }
        $oauth = $this->mpWecaht->oauth->scopes(['snsapi_userinfo']);
        $user = $oauth->userFromCode($code);
        $getTokenResponse = $user->getTokenResponse();
        if(isset($getTokenResponse['is_snapshotuser']) && $getTokenResponse['is_snapshotuser'] == 1){    
        }else{
            $openid =  $user->getId();
            $nickname =  $user->getName();
            $avatar =  $user->getAvatar();
            if($this->auth->loginOpenid($openid)==false){
                $user = User::where('openid',$openid)->find();
                if(empty($user)){
                    $user = new User;
                    Db::startTrans();
                    try {
                        $user->openid = $openid;
                        $user->nickname = $nickname;
                        $user->avatar = $avatar;
                        $user->save();
                        Db::commit();
                    } catch (\think\Exception $e) {
                        Db::rollback();
                    }
                }
                Session::set('lifeOpenid',$openid);
            }
        }
        return redirect(url(str_replace('_','/',$skip)));
    }
}